<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use backend\models\course\Course;
use backend\models\course\CourseType;
use backend\models\course\CourseRank;
use backend\models\course\CourseSource;
use backend\models\course\CourseCategory;
use backend\models\course\CoursePeriod;
use backend\models\course\CourseCart;
use backend\models\course\CourseOrder;
use backend\models\course\CourseOrderInfo;
use backend\models\article\Comment;
use frontend\models\question\Question;
use frontend\models\course\CourseQues;
use frontend\models\question\Answer;
use frontend\models\question\Ques;
use frontend\models\question\Queslabel;
use backend\models\course\LearnLog;
use frontend\models\User;
use frontend\models\UserCourse;
use yii\data\Pagination;
use backend\models\Collection;
use frontend\models\course\CourseInfo;
/*
*	课程
*/
class CourseController extends Controller{

	/**
	 * @inderitdoc 验证码配置
	 */
	public function actions()
	{
		return [
			'captcha'=>[
				'class'=>'yii\captcha\CaptchaAction',
				'maxLength'=>5,
				'minLength'=>5,
			],
		];
	}
	//课程首页展示
	public function actionIndex(){
		$Course 		= new Course;  			//实例化课程模型层
		$CourseType     = new CourseType;		//类型
		$CourseRank     = new CourseRank;		//级别
		$CourseSource   = new CourseSource;		//来源
		$CourseCategory = new CourseCategory;	//类别
		$type           = $CourseType     -> Type();
		$rank           = $CourseRank     -> Rank();
		$cate           = $CourseCategory -> Cate();
		$source         = $CourseSource   -> Source();
		//接受查询分类
		$keyword = YII::$app->request->get('1');
		$new_key = YII::$app->request->get('2');
		if ($new_key) {
			foreach ($new_key as $key => $value) {
				$keyword[$key] = $value;
			}
		}
		//获取课程列表
		$course 	= $Course -> CourseList($keyword);
		$pagination = $course['pagination'];
		unset($course['pagination']);
		$session   = YII::$app->session;
		$session->open();
		echo 2;
		echo $user_id   = $session->get('user_id');
		echo 1;
		return $this->render('index',[
							'type'       => $type,
							'rank'       => $rank,
							'cate'       => $cate,
							'source'     => $source,
							'course'     => $course,
							'keyword'    => $keyword,
							'new_key'    => $new_key,
							'pagination' => $pagination,
							'user_id'    => $user_id,
		]);
	}

    /**
     * 方法执行前
     */

    public function beforeAction($action){
        //父类方法
        parent::beforeAction($action);

        //未登陆允许访问的方法
        $allow = ['index'];

        //检测session
        $session   = YII::$app->session;
        $user_id   = $session->get('user_id');

        if (! $user_id && !in_array( $action->id, $allow)) {
            $this->goHome();
            return false;
        }

        return true;
    }


	/**
	 * 课程详情
	 */
	public function actionCourseDetail()
	{
		$request   = YII::$app->request;
    	$course_id = $request->get('course_id');
    	$session   = YII::$app->session;
    	$session  ->open();
    	$user_id   = $session->get('user_id');

		$is_add    = UserCourse::find()
    								->where("user_id=$user_id and course_id=$course_id")
    								->asArray()->one();
    	if ($is_add) {
    		$this->redirect(array('/course/play-movie','course_id'=>$course_id));
    	}

		$Course            = new Course;
		//获取课程目录
		$course['catalog'] = Course::CourseCatalog($course_id);
		$course['detail']  = $Course->CourseDetail($course_id);
		$course['comment'] = Comment::find()->where("comment_type=0 and model_id=$course_id")->with('user')->asArray()->all();
		//var_dump($course['detail']);die;
		return $this->render('new_detail',['course'=>$course]);
	}

	/**
	 * 课程播放
	 */
	public function actionPlayMovie()
	{
		$Course    = new Course;
		$request   = YII::$app->request;
		$session   = YII::$app->session;
		$session->open();
		$user_id   = $session->get('user_id');
		$course_id = $request->get('course_id');
		$period_id = $request->get('period_id');
		//获取视频地址
		if ($period_id) {
			$movie     = CoursePeriod::findOne($period_id);
		}else{
			$movie     = CoursePeriod::find()->where("course_id=$course_id")->one();
			$period_id = $movie->period_id;
		}

		//更改学习记录
		$LearnLog = LearnLog::find()->where(['user_id'   => $user_id,
											 'course_id' => $course_id,
											 'period_id' => $period_id,
											 ])
									->one();

		if ($LearnLog) {
			$LearnLog ->videoStatus ='playing';
			$LearnLog ->updateTime  = time();
			$LearnLog ->watchNum 	= $LearnLog->watchNum+1;
			$LearnLog ->save();
		}else{
			$LearnLog = new LearnLog;
			$LearnLog ->user_id     = $user_id;
			$LearnLog ->course_id   = $course_id;
			$LearnLog ->period_id   = $period_id;
			$LearnLog ->status      ='learning';
			$LearnLog ->videoStatus ='playing';
			$LearnLog ->startTime   = time();
			$LearnLog ->updateTime  = time();
			$LearnLog ->watchNum    = 1;
			$re = $LearnLog ->save();
		}
		$course['catalog'] = Course::CourseCatalog($course_id);
		$course['detail']  = $Course->CourseDetail($course_id);
		$course['comment'] = Comment::find()->where("comment_type=0 and model_id=$course_id")->with('user')->orderby("comment_addtime desc")->limit(5)->asArray()->all();
		$model      = new CourseInfo;
		$info       = new Question;
		$labels     = $info->labels();
		$CourseQues = new CourseQues;
		$data       = $CourseQues->CourseQues($course_id);
		/**/
		foreach ($data as $key => $answer) {
			$ques_id = $answer['ques_id'];
			$answers = Answer::find()->where("ques_id = $ques_id")->orderby("answer_addtime desc")->asarray()->one();
			$data[$key]['answers'] = $answers;
		}
		return $this->render("playmovie",['model'=>$model,'movie'=>$movie,'course'=>$course,'user_id'=>$user_id,'course_id'=>$course_id,'labels'=>$labels,'data'=>$data]);
	}

	/**
	 * 观看视频记录
	 */
	public function actionLearnLog()
	{
		$request  = YII::$app->request;
		$log      = $request ->get();
		$status   = $request ->get('status');

		$LearnLog = LearnLog::find()->where(['user_id'  =>$log['user_id'],
											 'course_id'=>$log['course_id'],
											 'period_id'=>$log['period_id']])
									->one();
		if ($LearnLog ->status != 'finished') {
			$LearnLog ->status 	= $status;
		}
		$LearnLog ->videoStatus = 'paused';
		$LearnLog ->updateTime  = time();
		$LearnLog ->save();
		if ($status=='finished') {
			UserCourse::MyCourse($log['user_id'],$log['course_id']);
		}
	}

	/**
	 * 添加到购物车
	 */

	public function actionAddCart()
	{
		$request   = YII::$app->request;
		$session   = YII::$app->session;
		$session  -> open();
		$user_id   = $session->get('user_id');
		if (!$user_id) {
			echo "请先登录";die;
		}
		$course = Course::findOne($request->get('course_id'));
		$re = CourseCart::find()->where("user_id=$user_id and course_id=$course->course_id")->asArray()->one();
		if (!$re) {
			//加入到购物车
			$CourseCart = new CourseCart;
			$CourseCart ->user_id      = $user_id;
			$CourseCart ->course_id    = $course->course_id;
			$CourseCart ->course_name  = $course->course_name;
			$CourseCart ->price 	   = $course->course_price;
			$CourseCart ->addtime      = time();
			$CourseCart ->save();
		}

		$cart         = CourseCart::find()->where("user_id=$user_id")->asArray()->all();
		$price_amount = 0;
		foreach ($cart as $k => $good) {
			$price_amount += $good['price'];
		}
		return $this->render('cart-first',['cart'=>$cart,'price_amount'=>$price_amount]);
	}
	/**
	 * 删除购物车
	 */
	public function actionDelCart()
	{
		$request = YII::$app->request;
		$cart_id = $request->get('cart_id');
		$re      = CourseCart::deleteAll("cart_id=$cart_id");
		echo $re ;
	}
	/**
	 * 订单信息
	 */
	public function actionOrder()
	{

		$request   = YII::$app->request;
		$session   = YII::$app->session;
		$session  -> open();
		$user_id   = $session->get('user_id');
		$cart 	   = CourseCart::find()->where("user_id=$user_id")->asArray()->all();
		$price_amount = 0;
		foreach ($cart as $k => $good) {
				$price_amount += $good['price'];
			}
		//提交订单
		if ($request->get('order')) {

			// 获取用户信息
			$User  = User::findOne($user_id);
			$coin  = $User ->user_virtual;
			// 生成订单
			$Order = new CourseOrder;
			$Order->user_name     = $User->user_name;
			$Order->user_id       = $User->user_id;
			$Order->user_phone    = $User->user_phone;
			$Order->user_email    = $User->user_email;
			$Order->order_addtime = time();
			$Order->price_amount  = $price_amount;
			$Order->order_sn      = uniqid();
			$Order->type      	  = 'course';
			//var_dump($Order);die;
			$re   = $Order->save();
			//var_dump($re);die;
			$order_id = Yii::$app->db->getLastInsertID();
			if ($re) {
				//生成订单详情
				foreach ($cart as $key => $good) {
					$OrderInfo = new CourseOrderInfo;
					$OrderInfo ->order_id    = $order_id;
					$OrderInfo ->course_id   = $good['course_id'];
					$OrderInfo ->course_name = $good['course_name'];
					$OrderInfo ->price       = $good['price'];

					$OrderInfo ->save();
				}
				//删除购物车
				CourseCart::deleteAll("user_id = $user_id");
			}
			$order = CourseOrder::findOne($order_id);
			return $this->render("cart-third",['order'=>$order,'coin'=>$coin]);
		}
		return $this->render("cart-second",['cart'=>$cart,'price_amount'=>$price_amount]);
	}



    /**
     * 课程侧边目录
     */
    public function actionSide()
    {
    	$course_id = YII::$app->request->get("course_id");
    	$type_id = Course::findOne($course_id)->type_id;
    	$course = Course::CourseCatalog($course_id);
    	//var_dump($course);die;
        return $this->renderPartial('course-side',['course'=>$course,'course_id'=>$course_id,'type_id'=>$type_id]);
    }

    /**
     * 加入课程
     */
    public function actionAddCourse()
    {
    	$request   = YII::$app->request;
    	$course_id = $request->get('course_id');
    	$session   = YII::$app->session;
    	$session  ->open();
    	$user_id   = $session->get('user_id');
    	if (!$session->get('user_id')) {
			echo "请先登录";die;
		}
    	$is_add    = UserCourse::find()
    								->where("user_id=$user_id and course_id=$course_id")
    								->asArray()->one();
    	if ($is_add) {
    		$this->redirect(array('/course/play-movie','course_id'=>$course_id));
    	}
    	$course    = Course::findOne($course_id);
    	if ($course->course_price >0) {
    		echo "请购买此课程";die;
    	}
    	$course   ->apply_num = $course ->apply_num+1;
    	$re = $course   ->save();

    	$result   = UserCourse::AddCourse($user_id,$course_id);
    	if ($result) {
    		$this->redirect(array('/course/play-movie','course_id'=>$course_id));
    	}else{
    		echo "失败";
    	}
    }

    /**
	 * @inheritdoc 收藏
	 */
	public function actionCollect()
	{
		$session = Yii::$app->session;
		$user_id = $session->get('user_id');
		$request = Yii::$app->request->get();
		$id = $request['id'];
		if($user_id){
			$collection = new Collection;
			$data = $collection -> collect($user_id,$id,2);
			if($data){
				return json_encode([
					'code' => 2,
					'msg'  => '您已收藏！',
				]);die;
			}else{
				$collection -> user_id = $user_id;
				$collection -> collect_type = 2;
				$collection -> model_id = $id;
				$collection -> collect_addtime = time();
				$res = $collection -> save();
				if($res){
					return json_encode([
						'code' => 3,
						'msg'  => '收藏成功',
					]);die;
				}else{
					return json_encode([
						'code' => 4,
						'msg'  => '收藏失败',
					]);die;
				}
			}
		}else{
			return json_encode([
					'code' => 1,
					'msg'  => '请先登录！',
				]);die;
		}
	}

	/**
	 * @inheritdoc 课程评论
	 */
	public function actionComment()
	{
		$course_id = yii::$app->request->post("course_id");
		$session = Yii::$app->session;
		$user_id = $session->get('user_id');
		$db = User::find()->where(['user_id'=>$user_id])->asarray()->one();
        $user_name = $db['user_name'];
		$str = Yii::$app->request->post("comment_content");
		/*$sql = "SELECT find,replacement from edu_Illegal WHERE instr($str,find)";*/
		/*$str = "我估算UI妮哦AV12次下跪拉萨路54式空间里看见爱上的女1夜情";*/
		if(empty($str))
		{
			$this->redirect(array('/course/play-movie','course_id'=>$course_id));die;
		}
		$arr = new Comment;
		$arr = $arr->CommentAdd($str);
		foreach ($arr as $key => $val)
		{
			$error = $val['find'];
			$replace = $val['replacement'];
			$info = preg_replace("/$error/",$replace,$str);
			$str=$info;
		}
		$model = new Comment;
		$model->comment_type 	= 0;
		$model->model_id     	= $course_id;
		$model->comment_addtime = time();
		$model->user_id			= $user_id;
		$model->user_name		= $user_name;
		$model->comment_content	= $str;
		$rs = $model->save();
		if($rs){
			$this->redirect(array('/course/play-movie','course_id'=>$course_id));
		}else{
			$this->redirect(array('/course/play-movie','course_id'=>$course_id));
		}
	}
	/**
	 * @inheritdoc 课程问答
	 */
	public function actionReply()
	{
		$course_id = yii::$app->request->post("course_id");
		$session = yii::$app->session;
		$user_id = $session->get("user_id");
		$db = User::find()->where(['user_id'=>$user_id])->asarray()->one();
    	$user_name = $db['user_name'];
		$info = yii::$app->request->post();
		$model = new Ques;
		$model->ques_name 		= $info['title'];
		$model->ques_content 	= $info['editorValue'];
		$model->ques_addtime	= time();
		$model->ques_type		= 1;
		$model->course_id		= $course_id;
		$model->user_id			= $user_id;
		$model->user_name		= $user_name;
		$rs = $model->save();
		$last_id = Yii::$app->db->getLastInsertID();
		$label_id = $info['label_id'];
		$label_id = explode(',', $label_id);
		foreach ($label_id as $key => $val) {
			$label = new Queslabel;
			$label->queslabel_id = $val;
			$label->ques_id 		= $last_id;
			$label->save();
		}
		if($rs)
		{
			$this->redirect(array('/course/play-movie','course_id'=>$course_id));
		}
		else
		{
			$this->redirect(array('/course/play-movie','course_id'=>$course_id));
		}
	}
	/**
	 *	支付
	 */
	public function actionOrderPay()
	{

		$order_id = YII::$app->request->get('order_id');
		$coin     = YII::$app->request->get('coin');
		$session  = yii::$app->session;
		$session  ->open();
		$user_id  = $session->get("user_id");
		$user 	  = User::find()->where("user_id=$user_id")->one();

		if ($user->user_virtual < $coin) {
			echo "数据异常";die;
		}
		$order = CourseOrder::findOne($order_id);
		$order ->coinAmount = $coin;
		if ($order ->price_amount - $coin<0) {
			$order ->amount = 0;
		}else{
			$order ->amount = $order ->price_amount - $coin;
		}
		$order ->save();

		//判断用户是否还需要支付现金
		if ($order ->amount == 0) {
			$user->user_virtual = $user->user_virtual-$coin;
			$user->save();
			//
			$order = CourseOrder::findOne($order_id);
			$order->order_status = 1;
			$order->save();
			$order_id = $order->order_id;
			$user_id  = $order->user_id;
			if ($order->type=='course') {
				$courses = CourseOrderInfo::find()->where("order_id=$order_id")->asArray()->all();
				foreach ($courses as $key => $course) {
					$result = UserCourse::AddCourse($user_id,$course['course_id']);
				}
			}
			echo "购买成功";die;
		}
		$this->redirect(array('/alipay/index','order_id'=>$order_id));
	}

}
?>